<?php
class st_cronjob_log_model extends stmodel_2_1{

    public function __construct($config) {
        parent::__construct ( $config );
        $this->setTableName($this->prefix.'st_cronjob_log');
        $this->setPrimaryKey('id');
    }

    public function saveCronLog($data) {
        $data['id'] = isset($data['id'])? $data['id']:NULL;
        
        return $this->saveRecords($data);
    }

    public function getID($name, $ctime){
        $query = "SELECT id FROM `{$this->_tableName}`
        WHERE `ctime` like('{$ctime}') AND `cronjob_name` like('{$name}')
        ";
//        echo $query; die;
        return $this->get_var($query);
    }

    public function countRecords($args = ''){
        $result = $this->getRecords($args);
        return count($result);

    }

    public function getCronjobName(){
        $query = "SELECT cronjob_name FROM `{$this->_tableName}`
        GROUP BY cronjob_name
        ";
//        echo $query; die;
        return $this->get_col($query);
    }
    
    public function cleanLog(){
        $month = intval(date('n')) - 3;
        $query = "SELECT * FROM $this->_tableName
        WHERE month(ctime) < {$month}";
        if($this->query($query)){
            $query = "DELETE FROM $this->_tableName
            WHERE month(ctime) < {$month}";
            return $this->query($query);
        }else{
            return true;
        }
                
        
    }
    
    public function numberOfExecuted(){
        $query = "SELECT status, count(id) AS num FROM `{$this->_tableName}`
        GROUP BY status
        ";
//        echo $query; die;
        $result = $this->get_results($query);
        $results = array();
        $results['fail'] = $result[0]->num;
        $results['success'] = $result[1]->num;
        return $results; 
    }
    
    public function getAllFailExecuted(){        
        $dayOfPreWeek = mktime(0, 0, 0, date('m'), date('d')-7, date('Y'));
        $numberOfday = date('w', $dayOfPreWeek);
        
        $dis = $numberOfday - 1;
        $startPreWeek = $dayOfPreWeek - ($dis * 24 * 60 * 60);
        $endPreWeek = date('Y-m-d H:i:s', $startPreWeek + (6 * 24 * 60 * 60));
        $startPreWeek = date('Y-m-d H:i:s', $startPreWeek);
        
        $query = "SELECT *, a.cronjob_name AS name FROM
        (SELECT cronjob_name, count(id) AS num1 FROM `{$this->_tableName}`
        WHERE status = 0 AND ctime >= '$startPreWeek' AND ctime <= '$endPreWeek'
        GROUP BY cronjob_name) AS a
        INNER JOIN 
        (SELECT cronjob_name, count(id) AS num2 FROM `{$this->_tableName}`
        WHERE status = 1 AND ctime >= '$startPreWeek' AND ctime <= '$endPreWeek'
        GROUP BY cronjob_name) AS b
        ON b.cronjob_name = a.cronjob_name
        ";
//        echo $query;die;
        return $results = $this->get_results($query);
    }
    
}